package com.cmcc.aregister.ui.activity;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.cmcc.aregister.MyApplication;
import com.cmcc.aregister.R;
import com.cmcc.aregister.cs.constant.Arguments;
import com.cmcc.aregister.cs.constant.ConfigUtilHelper;
import com.cmcc.aregister.cs.constant.GlobalSetting;
import com.cmcc.aregister.cs.http.HttpAsyncTask;
import com.cmcc.aregister.cs.lazyimage.LazyImageView;
import com.cmcc.aregister.cs.model.Doctor;
import com.cmcc.aregister.cs.model.Schedule;
import com.cmcc.aregister.cs.util.PotoalParcelable;
import com.cmcc.aregister.cs.util.Utils;
import com.cmcc.aregister.ui.adapter.DoctorDetailAdapter;

/**
 * 医生详情
 * @author Administrator
 * 
 */
public class DoctorDetailActivity extends ParentActivity
{
    private static final String TAG = "DoctorDetailActivity";
    // ------view------
    // private TextView home_situation;
    private ImageView attention_layout;
    private Button cancel_btn;
    private Button reserve_btn;
    // ------parameter------
    private Doctor doctor;
    private Schedule schedule;
    private String attention;
    private int position;
    private String area_type;

    private String[] array_sch;
    // ------------

    int total_left_num = 0;// 该医生总号源数

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        init(R.layout.p_doctor_detail);
    }

    @Override
    protected void setupData()
    {
        Map<String, Object> httpMap = ((PotoalParcelable) getIntent()
            .getParcelableExtra(Arguments.INTENT_TO_NEXT_PAGE)).map;
        doctor = (Doctor) httpMap.get(Arguments.ACTIVITY_JUMP_DOCTOR);
        position = (Integer) httpMap.get(Arguments.ACTIVITY_JUMP_POSITION);
        area_type = (String) httpMap.get(Arguments.ACTIVITY_JUMP_AREA_TYPE);
        if (doctor.schedule_list != null && doctor.schedule_list.size() > 0)
        {
            Collections.sort(doctor.schedule_list);
            for (Schedule s : doctor.schedule_list)
            {
                total_left_num += Integer.valueOf(s.left_num);
            }
            schedule = doctor.schedule_list.get(0);
        }
        sendGetDoctorDetailTask(ConfigUtilHelper.getMobile(app), area_type,
            doctor.dep_id, doctor.doctor_id);
    }

    @Override
    protected void setupView()
    {
        ((ImageView) findViewById(R.id.title))
            .setBackgroundResource(R.drawable.doctor_detail_title);
        ((TextView) findViewById(R.id.name)).setText(doctor.doctor_name);
        ((TextView) findViewById(R.id.unit_name)).setText(doctor.unit_name);
        ((TextView) findViewById(R.id.doctor_post)).setText(doctor.dep_name);
        ((LazyImageView) findViewById(R.id.image))
            .loadImage(doctor.image, 0, 1);
        attention_layout = (ImageView) findViewById(R.id.attention_layout);
        // home_situation = (TextView) findViewById(R.id.home_situation);
        // ((TextView) findViewById(R.id.doctor_desc))
        // .setMovementMethod(ScrollingMovementMethod.getInstance());
        // home_situation.setMovementMethod(ScrollingMovementMethod.getInstance());
        // home_situation.setOnClickListener(onClickListener);
        cancel_btn = (Button) findViewById(R.id.cancel_btn);
        reserve_btn = (Button) findViewById(R.id.reserve_btn);
        // reserve_btn.setEnabled(false);
        cancel_btn.setOnClickListener(onClickListener);
        reserve_btn.setOnClickListener(onClickListener);
        // StringBuffer sb = new StringBuffer();
        // if (doctor.schedule_list != null) {
        int len = doctor.schedule_list.size();
        Collections.sort(doctor.schedule_list);
        array_sch = new String[len];
        for (int i = 0; i < len; i++)
        {
            Schedule sch = doctor.schedule_list.get(i);
            String sch_txt = sch.to_date + " " + sch.time_type + " "
                + getString(R.string.left_num) + "(" + sch.left_num + ")";
            // sb.append(sch_txt + "\n");
            array_sch[i] = sch_txt;
        }
        // /*
        // * for (Schedule sch : doctor.schedule_list) {
        // * Log.i("12345","doctor.schedule_list:" + sch.to_date);
        // * sb.append(sch.to_date + " " + sch.time_type + " " +
        // * getString(R.string.left_num) + "(" + sch.left_num + ")\n"); }
        // */
        // home_situation.setText(sb);
        // }
        // else {
        // home_situation.setText("");
        // reserve_btn.setEnabled(false);
        // }
        // if (home_situation.getText().toString().trim().equals("")) {
        // home_situation.setText(getString(R.string.msg_no_resource));
        // reserve_btn.setEnabled(false);
        // }
        // else {
        // reserve_btn.setEnabled(true);
        // }
        //
        if (doctor.schedule_list != null)
        {
            ListView listView = (ListView) findViewById(R.id.home_situation);
            listView.setAdapter(new DoctorDetailAdapter(this,
                doctor.schedule_list));
            listView.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3)
                {
                    if (!ConfigUtilHelper.isLogin(app))
                    {
                        gotoLogin();
                        return;
                    }
                    if ("0".equals(doctor.area_type) && total_left_num == 0)
                    {
                        showSingleAlertDlg(getString(R.string.notice),
                            getString(R.string.no_left_num),
                            getString(R.string.close));
                    }
                    else
                    {
                        showSingleDlg();
                    }
                }
            });
        }
        else
        {
            ((TextView) findViewById(R.id.tv_doctor_not))
                .setVisibility(View.VISIBLE);
            reserve_btn.setEnabled(false);
        }
        //
        attention = MyApplication.getInstance().doctorMap.get(doctor.doctor_id);
        if (attention == null || "".equals(attention))
        {
            attention = doctor.is_attention;
        }
        if ("1".equals(attention))
        {
            cancel_btn.setText(R.string.cancel_attention);
            attention_layout.setVisibility(View.VISIBLE);
            cancel_btn.setBackgroundResource(R.drawable.left_btn_cancel_bg);
        }
        else
        {
            cancel_btn.setText(R.string.confim_attention);
            attention_layout.setVisibility(View.GONE);
            cancel_btn.setBackgroundResource(R.drawable.left_btn_affirm_bg);
        }
    }

    public void setView()
    {
        if (doctor.detail != null)
        {
            ((TextView) findViewById(R.id.doctor_desc)).setText(doctor.detail);
            if (((TextView) findViewById(R.id.doctor_desc)).getText()
                .toString().trim().equals(""))
            {
                ((TextView) findViewById(R.id.doctor_desc))
                    .setText(getString(R.string.no_person_data));
            }
        }
        else
        {
            ((TextView) findViewById(R.id.doctor_desc))
                .setText(getString(R.string.no_person_data));
        }

    }

    // 跳转到登陆界面
    private void gotoLogin()
    {
        Intent intent = new Intent(DoctorDetailActivity.this,
            UserLoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    OnClickListener onClickListener = new OnClickListener() {
        @Override
        public void onClick(View v)
        {
            int id = v.getId();
            if (id == R.id.cancel_btn)
            {
                if (!ConfigUtilHelper.isLogin(app))
                {
                    gotoLogin();
                    return;
                }
                else if ("1".equals(doctor.is_attention))
                {
                    sendCancelAttentionTask(ConfigUtilHelper.getMobile(app),
                        "2", area_type, doctor.doctor_id);
                }
                else
                {
                    sendConfirmAttentionTask(ConfigUtilHelper.getMobile(app),
                        "2", area_type, doctor.doctor_id);
                }
            }
            // else if (id == R.id.reserve_btn || id == R.id.home_situation) {
            else if (id == R.id.reserve_btn)
            {
                if (!ConfigUtilHelper.isLogin(app))
                {
                    gotoLogin();
                    return;
                }
                if ("0".equals(doctor.area_type) && total_left_num == 0)
                {

                    showSingleAlertDlg(getString(R.string.notice),
                        getString(R.string.no_left_num),
                        getString(R.string.close));
                }
                else
                {
                    // showDialog(DIALOG);
                    showSingleDlg();
                }
            }
        }
    };

    private void chooseSch()
    {
        Intent intent = new Intent(DoctorDetailActivity.this,
            AppointmentActivity.class);
        Map<String, Object> httpMap = new HashMap<String, Object>();
        PotoalParcelable potoal = new PotoalParcelable(httpMap);
        intent.putExtra(Arguments.ACTIVITY_JUMP_SCREENING_TYPE, 2);
        httpMap.put(Arguments.ACTIVITY_JUMP_UNIT_ID, doctor.unit_id);
        httpMap.put(Arguments.ACTIVITY_JUMP_CHOICE_HOSPITAL, doctor.unit_name);
        httpMap.put(Arguments.ACTIVITY_JUMP_DEP_ID, doctor.dep_id);
        httpMap.put(Arguments.ACTIVITY_JUMP_CHOICE_DEPARTMENT, doctor.dep_name);
        if ("0".equals(doctor.area_type))
        {
            httpMap.put(Arguments.ACTIVITY_JUMP_SCHEDULE_ID,
                schedule.schedule_id);
            httpMap.put(Arguments.ACTIVITY_JUMP_CHOICE_DOCTOR,
                doctor.doctor_name + " " + schedule.to_date + " "
                    + schedule.time_type);
            httpMap.put(Arguments.ACTIVITY_JUMP_GUAHAO_AMT, doctor.guahao_amt);
        }
        else
        {
            httpMap.put(Arguments.ACTIVITY_JUMP_CHOICE_DOCTOR,
                doctor.doctor_name);
            httpMap.put(Arguments.ACTIVITY_JUMP_DOCTOR_ID, doctor.doctor_id);
        }
        httpMap.put(Arguments.ACTIVITY_JUMP_AREA_TYPE, doctor.area_type);
        intent.putExtra(Arguments.INTENT_TO_NEXT_PAGE, potoal);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    private void showSingleDlg()
    {
        Builder builder = new android.app.AlertDialog.Builder(this);
        // 设置对话框的图标
        builder.setIcon(android.R.drawable.ic_dialog_info);
        // 设置对话框的标题
        builder.setTitle(getString(R.string.choose_mast));
        // 0: 默认第一个单选按钮被选中
        builder.setSingleChoiceItems(array_sch, lastChooseIndex,
            singleOnClickListener);
        // 添加一个确定按钮
        builder.setPositiveButton(getString(R.string.dialog_sure),
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which)
                {
                    chooseSch();
                }
            });
        // 创建一个单选按钮对话框
        dialog = builder.create();
        dialog.show();
    }

    /*
     * ophone手机不支持这种写法 private final static int DIALOG = 1;
     * 
     * @Override protected Dialog onCreateDialog(int id, Bundle args) {
     * 
     * // TODO Auto-generated method stub Dialog dialog=null; switch (id) { case
     * DIALOG: Builder builder = new android.app.AlertDialog.Builder(this);
     * //设置对话框的图标 builder.setIcon(android.R.drawable.ic_dialog_info); //设置对话框的标题
     * builder.setTitle(getString(R.string.choose_mast)); //0: 默认第一个单选按钮被选中
     * builder.setSingleChoiceItems(array_sch, 0, singleOnClickListener);
     * //添加一个确定按钮 builder.setPositiveButton(getString(R.string.dialog_sure), new
     * DialogInterface.OnClickListener(){ public void onClick(DialogInterface
     * dialog, int which) { chooseSch(); } }); //创建一个单选按钮对话框
     * dialog=builder.create(); break; } return dialog; }
     */
    int lastChooseIndex;
    android.content.DialogInterface.OnClickListener singleOnClickListener = new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which)
        {
            // TODO Auto-generated method stub
            lastChooseIndex = which;
            Collections.sort(doctor.schedule_list);
            schedule = doctor.schedule_list.get(lastChooseIndex);
        }
    };

    /**
     * 我要关注
     */
    private HttpAsyncTask sendConfirmAttentionTask;

    /**
     * 
     * @param mobile 手机号码
     * @param attentionType 关注类别 N 0：关注医院1:关注科室2:关注医生
     * @param area_type 医院区域 N 0：本地 1是异地
     * @param id 相应id
     */
    private void sendConfirmAttentionTask(String mobile, String attentionType,
        String area_type, String id)
    {
        logger.d("----------sendConfirmAttentionTask----------");
        Map<String, String> parameterMap = new HashMap<String, String>();
        parameterMap.put("mobile", mobile);
        parameterMap.put("area_type", area_type);
        parameterMap.put("attentionType", "2");
        parameterMap.put("doctor_id", id);
        String confirmAttentionUrl = Utils.changeUrl(
            Arguments.SERVER_URL_CONFIRM_ATTENTION, parameterMap);
        sendConfirmAttentionTask = new HttpAsyncTask(HttpAsyncTask.GET,
            GlobalSetting.XML_CONFIRM_ATTENTION, confirmAttentionUrl,
            HttpAsyncTask.CACHE_TYPE_ACTION, false);
        showProgressDialog();
        sendConfirmAttentionTask.setUIHandler(sendConfirmAttentionTaskHandler);
        mHttpManager.execute(sendConfirmAttentionTask);
    }

    @SuppressWarnings("unchecked")
    Handler sendConfirmAttentionTaskHandler = new Handler() {
        public void handleMessage(Message msg)
        {
            logger.d("----------sendConfirmAttentionTaskHandler----------");
            switch (msg.what)
            {
            case HttpAsyncTask.TASK_NOTIFY_RETURN_DATA:
                dismissProgressDialog();
                if (msg.obj != null)
                {
                    try
                    {
                        Map<String, Object> httpMap = (Map<String, Object>) msg.obj;
                        String status = (String) httpMap
                            .get(Arguments.XML_STATUS);
                        String message = (String) httpMap
                            .get(Arguments.XML_MESSAGE);
                        if ("0".equals(status))
                        {
                            attention_layout.setVisibility(View.VISIBLE);
                            cancel_btn.setText(R.string.cancel_attention);
                            cancel_btn
                                .setBackgroundResource(R.drawable.left_btn_cancel_bg);
                            doctor.is_attention = "1";
                        }
                        showSingleAlertDlg(getString(R.string.notice), message,
                            getString(R.string.close));
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
                else
                {
                    showSingleAlertDlg(getString(R.string.notice),
                        getString(R.string.attention_fail),
                        getString(R.string.close));
                }
                break;
            case HttpAsyncTask.TASK_NOTIFY_CONNECTION_FAIL:
                dismissProgressDialog();
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.attention_fail),
                    getString(R.string.close));
                break;
            }
        }
    };

    /**
     * 取消关注
     */
    private HttpAsyncTask sendCancelAttentionTask;

    /**
     * 
     * @param mobile 手机号码
     * @param attentionType 关注类别 N 0：关注医院1:关注科室2:关注医生
     * @param area_type area_type 区域ID Y 0是本地 1是异地 2是全部
     * @param id 相应id
     */
    private void sendCancelAttentionTask(String mobile, String attentionType,
        String area_type, String id)
    {
        logger.d("----------sendCancelAttentionTask----------");
        Map<String, String> parameterMap = new HashMap<String, String>();
        parameterMap.put("mobile", mobile);
        parameterMap.put("area_type", area_type);
        parameterMap.put("attentionType", "2");
        parameterMap.put("doctor_id", id);
        String cancelAttentionUrl = Utils.changeUrl(
            Arguments.SERVER_URL_CANCEL_ATTENTION, parameterMap);
        sendCancelAttentionTask = new HttpAsyncTask(HttpAsyncTask.GET,
            GlobalSetting.XML_CANCEL_ATTENTION, cancelAttentionUrl,
            HttpAsyncTask.CACHE_TYPE_ACTION, false);
        showProgressDialog();
        sendCancelAttentionTask.setUIHandler(sendCancelAttentionTaskHandler);
        mHttpManager.execute(sendCancelAttentionTask);
    }

    @SuppressWarnings("unchecked")
    Handler sendCancelAttentionTaskHandler = new Handler() {
        public void handleMessage(Message msg)
        {
            logger.d("----------sendCancelAttentionTaskHandler----------");
            switch (msg.what)
            {
            case HttpAsyncTask.TASK_NOTIFY_RETURN_DATA:
                dismissProgressDialog();
                if (msg.obj != null)
                {
                    try
                    {
                        Map<String, Object> httpMap = (Map<String, Object>) msg.obj;
                        String status = (String) httpMap
                            .get(Arguments.XML_STATUS);
                        String message = (String) httpMap
                            .get(Arguments.XML_MESSAGE);
                        if ("0".equals(status))
                        {
                            attention_layout.setVisibility(View.GONE);
                            cancel_btn.setText(R.string.confim_attention);
                            cancel_btn
                                .setBackgroundResource(R.drawable.left_btn_affirm_bg);
                            doctor.is_attention = "0";
                        }
                        showSingleAlertDlg(getString(R.string.notice), message,
                            getString(R.string.close));
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
                else
                {
                    showSingleAlertDlg(getString(R.string.notice),
                        getString(R.string.cancel_fail),
                        getString(R.string.close));
                }
                break;
            case HttpAsyncTask.TASK_NOTIFY_CONNECTION_FAIL:
                dismissProgressDialog();
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.cancel_fail), getString(R.string.close));
                break;
            }
        }
    };

    /**
     * 获取医生信息
     */
    private HttpAsyncTask sendGetDoctorDetailTask;

    /**
     * 
     * @param mobile 手机号码 如果为空，则不处理关注相关数据
     * @param area_type 区域类别 0：本地 1：异地
     * @param dep_id 科室id
     * @param doctor_id 医生id
     */
    private void sendGetDoctorDetailTask(String mobile, String area_type,
        String dep_id, String doctor_id)
    {
        logger.d("----------sendGetDoctorDetailTask----------");
        Map<String, String> parameterMap = new HashMap<String, String>();
        parameterMap.put("area_type", area_type);
        parameterMap.put("mobile", mobile);
        parameterMap.put("dep_id", dep_id);
        parameterMap.put("doctor_id", doctor_id);
        String getDoctorDetailUrl = Utils.changeUrl(
            Arguments.SERVER_URL_GET_DOCTOR_DETAIL, parameterMap);
        if (ConfigUtilHelper.debug)
        {
            Log.i(TAG, "查询医生详情url:" + getDoctorDetailUrl);
        }
        sendGetDoctorDetailTask = new HttpAsyncTask(HttpAsyncTask.GET,
            GlobalSetting.XML_DOCTOR_DETAIL, getDoctorDetailUrl,
            HttpAsyncTask.CACHE_TYPE_ACTION, false);
        showProgressDialog();
        sendGetDoctorDetailTask.setUIHandler(sendGetDoctorDetailTaskHandler);
        mHttpManager.execute(sendGetDoctorDetailTask);
    }

    @SuppressWarnings("unchecked")
    Handler sendGetDoctorDetailTaskHandler = new Handler() {
        public void handleMessage(Message msg)
        {
            logger.d("----------sendGetDoctorDetailTaskHandler----------");
            switch (msg.what)
            {
            case HttpAsyncTask.TASK_NOTIFY_RETURN_DATA:
                dismissProgressDialog();
                if (msg.obj != null)
                {
                    try
                    {
                        Map<String, Object> httpMap = (Map<String, Object>) msg.obj;
                        String detail = (String) httpMap
                            .get(Arguments.XML_DETAIL);
                        doctor.detail = detail;
                        setView();
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
                else
                {
                    showSingleAlertDlg(getString(R.string.notice),
                        getString(R.string.read_fail),
                        getString(R.string.close));
                }
                break;
            case HttpAsyncTask.TASK_NOTIFY_CONNECTION_FAIL:
                dismissProgressDialog();
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.read_fail), getString(R.string.close));
                break;
            }
        }
    };

    @Override
    protected void setTaskHandlerNull()
    {
        if (sendGetDoctorDetailTask != null)
        {
            sendGetDoctorDetailTask.setTaskBindingHandler(null);
        }
        if (sendConfirmAttentionTask != null)
        {
            sendConfirmAttentionTask.setTaskBindingHandler(null);
        }
        if (sendCancelAttentionTask != null)
        {
            sendCancelAttentionTask.setTaskBindingHandler(null);
        }
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        if (!doctor.is_attention.equals(attention))
        {
            app.changeAttention(2, doctor.doctor_id, position,
                doctor.is_attention);
        }
    }
}